from flask import Blueprint, redirect, render_template, request, jsonify, abort, url_for
from flask_login import login_required, current_user
from ..services import svc_dev_env_imgs
from ..baseapp import OperationalError

bp_dev_env_imgs = Blueprint("bp_dev_env_imgs", __name__, url_prefix="/dev_env_imgs")


@bp_dev_env_imgs.route("/editpanel")
@login_required
def editpanel():
    return render_template("dev_env_imgs.html")


@bp_dev_env_imgs.route("/create", methods=["POST"])
@login_required
def create_dev_env_img():
    data = request.json
    try:
        new_env = svc_dev_env_imgs.create_dev_env_img(**data)
        return jsonify({"id": new_env.id}), 201
    except OperationalError as e:
        return jsonify({"error": e.msg}), 400


@bp_dev_env_imgs.route("/<int:env_id>", methods=["GET"])
@login_required
def get_dev_env_img(env_id):
    env = svc_dev_env_imgs.get_dev_env_img_by_id(env_id)
    if not env:
        return jsonify({"error": "Not found"}), 404
    return jsonify(
        {
            "id": env.id,
            "name": env.name,
            "img_tag": env.img_tag,
            "description": env.description,
            "git_repositories": env.git_repositories,
            "editor_type": env.editor_type,
        }
    )


@bp_dev_env_imgs.route("/dev_env_imgs", methods=["GET"])
@login_required
def get_all_dev_env_imgs():
    envs = svc_dev_env_imgs.get_all_dev_env_imgs()
    return jsonify(
        [
            {
                "id": env.id,
                "name": env.name,
                "img_tag": env.img_tag,
                "description": env.description,
                "git_repositories": env.git_repositories,
                "editor_type": env.editor_type,
            }
            for env in envs
        ]
    )


@bp_dev_env_imgs.route("/<int:env_id>", methods=["PUT"])
@login_required
def update_dev_env_img(env_id):
    data = request.json
    updated_env = svc_dev_env_imgs.update_dev_env_img(env_id, **data)
    if not updated_env:
        return jsonify({"error": "Not found"}), 404
    return jsonify(
        {
            "id": updated_env.id,
            "name": updated_env.name,
            "img_tag": updated_env.img_tag,
            "description": updated_env.description,
            "git_repositories": updated_env.git_repositories,
            "editor_type": updated_env.editor_type,
        }
    )


@bp_dev_env_imgs.route("/<int:env_id>", methods=["DELETE"])
@login_required
def delete_dev_env_img(env_id):
    deleted = svc_dev_env_imgs.delete_dev_env_img(env_id)
    if not deleted:
        return jsonify({"error": "Not found"}), 404
    return jsonify({"message": "Deleted"}), 200


@bp_dev_env_imgs.route("/export_table", methods=["GET"])
@login_required
def export_table():
    csv_data = svc_dev_env_imgs.export_dev_env_imgs_to_csv()
    return (
        csv_data,
        200,
        {
            "Content-Type": "text/csv",
            "Content-Disposition": "attachment; filename=dev_env_imgs.csv",
        },
    )


@bp_dev_env_imgs.route("/import_table", methods=["POST"])
@login_required
def import_table():
    if "file" not in request.files:
        return jsonify({"error": "No file part"}), 400
    file = request.files["file"]
    if file.filename == "":
        return jsonify({"error": "No selected file"}), 400
    if file and file.filename and file.filename.endswith(".csv"):
        csv_data = file.read().decode("utf-8")
        try:
            svc_dev_env_imgs.import_dev_env_imgs_from_csv(csv_data)
            return jsonify({"message": "Data imported successfully"}), 200
        except Exception as e:
            return jsonify({"error": str(e)}), 400
    else:
        return jsonify({"error": "Invalid file type"}), 400


# 添加错误处理函数以捕获401错误并重定向到登录页面
@bp_dev_env_imgs.errorhandler(401)
def unauthorized_access(error):
    return redirect(url_for("login"))  # 假设登录页面的路由名为 'login'
